package com.ms.education.acl.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONObject;
import com.ms.education.JwtUtils;
import com.ms.education.R;
import com.ms.education.acl.entity.Permission;
import com.ms.education.acl.service.PermissionService;
import com.ms.education.exceptionHandler.EduException;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 权限 前端控制器
 * </p>
 *
 * @author ms
 * @since 2023-02-18
 */
@RestController
@RequestMapping("/acl/permission")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    @SaCheckPermission("permission.list")
    @ApiOperation("查询所有权限菜单")
    @GetMapping("indexAllPermission")
    public R indexAllPermission() {
        List<Permission> permissions = permissionService.queryAllPermission();
        return R.ok().data("permissions", permissions);
    }

    @SaCheckPermission("permission.remove")
    @ApiOperation("递归删除菜单")
    @DeleteMapping("remove/{id}")
    public R remove(@PathVariable("id") Integer id) {
        permissionService.remove(id);
        return R.ok();
    }

    @SaCheckPermission("role.acl")
    @ApiOperation("给角色分配权限")
    @PostMapping("doAssign/{roleId}")
    public R doAssign(@PathVariable("roleId") Integer roleId,
                      @RequestBody Integer[] permissionIds) {
        //System.out.println("*****************"+Arrays.toString(permissionIds));
        permissionService.doAssign(roleId, permissionIds);
        return R.ok();
    }

    @SaCheckPermission("permission.list")
    @ApiOperation("根据角色获取菜单")
    @GetMapping("toAssign/{roleId}")
    public R toAssign(@PathVariable("roleId") Integer roleId) {
        List<Permission> permissions = permissionService.toAssign(roleId);
        return R.ok().data("permissions", permissions);
    }

    @SaCheckPermission("permission.add")
    @ApiOperation("新增菜单")
    @PutMapping("save")
    public R save(Permission permission) {
        permissionService.save(permission);
        return R.ok();
    }

    @SaCheckPermission("permission.update")
    @ApiOperation("修改菜单")
    @PostMapping("update")
    public R update(@RequestBody Permission permission) {
        permissionService.updateById(permission);
        return R.ok();
    }

    @SaCheckLogin
    @GetMapping("menu")
    public R getMenu() {
        List<JSONObject> permissionList = permissionService.getMenu(Convert.toInt(StpUtil.getLoginId()));
        return R.ok().data("permissionList", permissionList);
    }




}
